const jwt = require('jsonwebtoken');

const axios = require('axios');
module.exports = () => {

  async function sendThird(key, role_id) {
    try {
      const port = await this.app.redis.get(`init:${this.app.config.auth.name}`);

      const config = {
        data: { key, role_id },
        method: 'post',
        url: `http://${this.app.config.auth.baseIp}:${port}/auth/checkout`,
      };

      const result = await axios(config);
      return result.data;
    } catch (error) {
      throw error;
    }
  }

  return async function(ctx, next) {
    try {
      let decode,
        role_id;
      let token = ctx.header.access_token;

      if (token) {
        token = token.replace('Bearer ', '');
        decode = jwt.decode(token);

        if (decode) {
          role_id = decode.role_id;
          ctx.session = decode;
        }
      }
      const key = ctx.method.toUpperCase() + ctx.routerPath.replace(/:/g, '').replace(/\//g, ':');

      // const { role_id } = jwt.decode(token);


      const checkout_result = await sendThird(key, role_id);

      if (checkout_result.data !== true) {
        throw new Error('当前账号权限不足');
      }
      await next();
    } catch (error) {
      ctx.status = 200;
      ctx.body = {
        code: 405,
        msg: 'failed',
        data: '当前账号权限不足',
      };
      return;
    }
  };
};
